package com.huxiu.yd.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.huxiu.yd.DiscoveryDetailActivity;
import com.huxiu.yd.R;
import com.huxiu.yd.ReviewListActivity;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.DiscoveryItem;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.Global;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.Settings;
import com.huxiu.yd.utils.Utils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by kHRYSTAL on 15/8/12:下午1:01.
 */
public class DiscoveryViewHolder implements OnClickListener {

    @InjectView(R.id.image)
    ImageView image;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.avatar)
    AvatarView avatar;

    @InjectView(R.id.name)
    TextView name;

    @InjectView(R.id.like_count)
    TextView likeCount;

    @InjectView(R.id.like_layout)
    FrameLayout likeLayout;

    @InjectView(R.id.comment_count)
    TextView commentCount;

    @InjectView(R.id.comment_layout)
    FrameLayout commentLayout;

    @InjectView(R.id.image_layout)
    FrameLayout imageLayout;

    @InjectView(R.id.circle_progress_bar)
    ProgressBar circleProgressBar;

    @InjectView(R.id.submitted)
    TextView submitted;

    @InjectView(R.id.all_count)
    TextView allCount;

    @InjectView(R.id.progress_layout)
    FrameLayout progressLayout;

    @InjectView(R.id.begin_time)
    TextView beginTime;

    @InjectView(R.id.divider)
    View divider;

    private DiscoveryItem item;

    private Context mContext;

    public static final int TYPE_DISCOVERY = 0;

    public static final int TYPE_MASSIVE_TEST = 1;

    private int type;

    private int height;

    public DiscoveryViewHolder(View view, Context context, int type) {
        ButterKnife.inject(this, view);
        this.type = type;
        mContext = context;
        commentLayout.setOnClickListener(this);
        image.setOnClickListener(this);
        LayoutParams params1 = (LayoutParams) imageLayout.getLayoutParams();
        params1.width = Global.screenWidth;
        height = type == TYPE_DISCOVERY ? Global.preferredImageHeight2 : Global.preferredImageHeight;
        params1.height = height;
        imageLayout.setLayoutParams(params1);
        FrameLayout.LayoutParams params2 = (FrameLayout.LayoutParams) image.getLayoutParams();
        params2.width = Global.screenWidth;
        params2.height = height;
        image.setLayoutParams(params2);
    }

    public void bindDiscoveryItem(DiscoveryItem item) {
        this.item = item;
        String imageUrl = item.image + "!" + height + "x" + Global.screenWidth;
        ImageLoader.getInstance()
                .displayImage(
                        imageUrl,
                        image, ImageUtils.getProductDisplayOption(item.getProductPlaceHolder()));
        if (type == TYPE_DISCOVERY) {
            avatar.setUserInfo(item.user_id, item.avatar, item.name);
            name.setOnClickListener(this);
            name.setCompoundDrawablesWithIntrinsicBounds(0, 0, item.getUserDrawable(), 0);
            likeLayout.setOnClickListener(this);
            title.setText(item.title);
            name.setText(item.name);
            beginTime.setVisibility(View.GONE);
            progressLayout.setVisibility(View.GONE);
            likeCount.setText(Integer.toString(item.like_num));
            likeCount.setTextColor(mContext.getResources().getColor(item.liked() ? R.color
                    .gray5 : R.color.gray4));
            commentCount.setText(Integer.toString(item.comment_num));
            likeCount.setCompoundDrawablesWithIntrinsicBounds(
                    item.liked() ? R.drawable.like_selected : R.drawable.like_normal, 0, 0, 0);
        } else {
            beginTime.setVisibility(View.VISIBLE);
            beginTime.setText("开始时间：" + Utils.getDateString(item.enroll_time));
            progressLayout.setVisibility(View.VISIBLE);
            avatar.setVisibility(View.GONE);
            title.setText(item.title);
            name.setText(item.company_name + "提供");
            name.setTextColor(mContext.getResources().getColor(R.color.gray4));
            likeCount.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            likeCount.setText(item.is_return == 0 ? R.string.no_return : R.string.should_return);
            commentCount.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            commentCount.setText(item.getEnrollStatusPrompt());
            commentCount.setTextColor(
                    mContext.getResources().getColor(item.getEnrollStatusColor()));
            submitted.setText(Integer.toString(item.member_num));
            allCount.setText(Integer.toString(item.member_max));
            circleProgressBar.setProgress(item.member_num * 100 / item.member_max);
        }
        title.setOnClickListener(this);
        divider.setBackgroundColor(item.getDividerColor());
    }

    private WeakReference<BaseAdapter> mAdapter;

    public void setAdapter(BaseAdapter adapter) {
        mAdapter = new WeakReference<>(adapter);
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.name:
                avatar.performClick();
                break;
            case R.id.title:
                //fall through
            case R.id.image:
                intent = new Intent(mContext, DiscoveryDetailActivity.class);
                intent.putExtra(type == TYPE_DISCOVERY ? Constants.DISCOVERY_ITEM_KEY
                        : Constants.MASSIVE_TEST_ITEM_KEY, item.toString());
                mContext.startActivity(intent);
                break;
            case R.id.like_layout:
                like();
                break;
            case R.id.comment_layout:
                intent = new Intent(mContext, ReviewListActivity.class);
                intent.putExtra(Constants.ARTICLE_ID_KEY, Integer.toString(item.id));
                mContext.startActivity(intent);
                break;
        }
    }

    private void like() {
        if (Settings.isLoggedIn()) {
            String url = NetworkConstants.DISCOVERY_URL;
            Map<String, String> params = new LinkedHashMap<>();
            params.put("act", "user_operate");
            params.put("article_id", String.valueOf(item.id));
            params.put("operate_type", "great_num");
            params.put("type", item.liked() ? "2" : "1");
            GsonRequest<BaseResponse> request = new GsonRequest<>(url, Method.POST, BaseResponse
                    .class,

                    true, params, new Listener<BaseResponse>() {
                @Override
                public void onResponse(BaseResponse response) {
                    if (response.isSuccess()) {
                        if (item.like_status == 1) {
                            item.like_num--;
                            item.like_status = 0;
                            Utils.showToast(R.string.unlike_success);
                        } else {
                            item.like_num++;
                            item.like_status = 1;
                            Utils.showToast(R.string.like_success);
                        }
                        if (mAdapter != null && mAdapter.get() != null) {
                            mAdapter.get().notifyDataSetChanged();
                        }
                    }
                }
            }, new ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Utils.showToast(R.string.generic_failure);
                }
            });
            NetworkHelper.getInstance().addToRequestQueue(request);
//            NetworkHelper.getInstance().getRequestQueue().start();
        } else {
            Utils.askLogIn((Activity) mContext);
        }
    }
}
